package com.axc.gallery2.net.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.axc.gallery2.R;
import com.axc.gallery2.Utils;
import com.axc.gallery2.dbhelper.NetAlbumDHhelper;
import com.axc.gallery2.dbhelper.NetPhotosInfo;
import com.axc.gallery2.edit.SinglePicZoom;
import com.axc.gallery2.net.AsyncDownPhotos;
import com.axc.gallery2.net.AsyncPhotoLoader;
import com.axc.gallery2.net.PhotosGetRequestParam;
import com.axc.gallery2.net.PhotosGetResponseBean;
import com.axc.gallery2.view.NetPhotosGridViewAdapter;
import com.renren.api.connect.android.Renren;
import com.renren.api.connect.android.common.AbstractRequestListener;
import com.renren.api.connect.android.exception.RenrenAuthError;
import com.renren.api.connect.android.exception.RenrenError;
import com.renren.api.connect.android.photos.PhotoBean;
import com.renren.api.connect.android.view.RenrenAuthListener;

public class NetAlbumActivity extends BaseActivity {

	/**
	 * 调用获取人人网相册API传入的method参数，必须参数
	 */
	// private static final String METHOD = "photos.get";

	private static final String KEY_AID = "aid";
	private static final String KEY_TITLE = "ablumName";
	private static final String KEY_RENREN = "renren";
	private long aid;// 网络相册aid
	private String title;// 网络相册名称n   
	private Renren renren;// 人人对像
	private Handler handler;
	private NetPhotosInfo uPhotosInfo;
	// private Bundle params = new Bundle();

	private NetPhotosGridViewAdapter netPhotosGridViewAdapter;
	private List<NetPhotosInfo> netPhotosInfos;
	private GridView gridView;
	private int w = 0;// GridView的宽度

	private LinearLayout mainLayout;

	/**
	 * 调用获取相册API接口需传入的参数
	 */
	PhotosGetRequestParam photosGetRequestParam = new PhotosGetRequestParam();

	private List<PhotoBean> photoList = new ArrayList<PhotoBean>();

	/**
	 * 菜单
	 */
	PopupWindow popupWindow;
	// 主题应用
	public static NetAlbumActivity Talbum;
	public int theme = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// 主题
		Talbum = this;
		theme = getSharedPreferences("cons", MODE_PRIVATE).getInt("theme",
				android.R.style.Theme);
		setTheme(theme);
		super.onCreate(savedInstanceState);
		// 菜单
		ListView listView = new ListView(this);
		List<String> list = new ArrayList<String>();
		list.add("查看");
		list.add("下载缩图");
		list.add("下载原图");
		DListAdapter listAdapter = new DListAdapter(this);
		listAdapter.setList(list);
		listView.setOnItemClickListener(listener);
		listView.setAdapter(listAdapter);
		popupWindow = new PopupWindow(this);
		popupWindow.setContentView(listView);
		popupWindow.setHeight(dip2px(120));
		popupWindow.setFocusable(true);
		popupWindow.setWidth(dip2px(80));
		aid = Long.decode(getIntent().getExtras().getString(KEY_AID));
		title = getIntent().getExtras().getString(KEY_TITLE);
		renren = (Renren) getIntent().getExtras().get(KEY_RENREN);

		// 初始化标题文字
		titlebarText.setText(title);

		photosGetRequestParam.setAid(aid);
		photosGetRequestParam.setUid(renren.getCurrentUid());

		mainLayout = (LinearLayout) getLayoutInflater().inflate(
				R.layout.net_album_folder_gridview, null);
		root.addView(mainLayout);

		getPhotos();

	}

	/**
	 * 菜单事件
	 */
	private OnItemClickListener listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			switch (position) {
			case 0:// 查看
				//优先查看原图
				String fileName = Environment.getExternalStorageDirectory()
				.getPath()
				+ "/DCIM/Gallery2/_"
				+ uPhotosInfo.getB_url().split("/")[uPhotosInfo.getB_url().split("/").length - 1];
				File file =new File(fileName);
				if(file.exists()){
					//显示相册
					Intent intent  = new Intent();
					intent.setClass(getBaseContext(), SinglePicZoom.class); 
					Bundle bundle=new Bundle();
					bundle.putString("img", fileName);
					intent.putExtra("imgdata", bundle);
					NetAlbumActivity.this.startActivity(intent);
				}else {
					//查看缩图
					fileName = Environment.getExternalStorageDirectory()
							.getPath()
							+ "/DCIM/Gallery2/_"
							+ uPhotosInfo.getS_url().split("/")[uPhotosInfo.getS_url().split("/").length - 1];
					file =new File(fileName);
					if(file.exists()){
						//显示相册
						Intent intent  = new Intent();
						intent.setClass(getBaseContext(), SinglePicZoom.class); 
						Bundle bundle=new Bundle();
						bundle.putString("img", fileName);
						intent.putExtra("imgdata", bundle);
						NetAlbumActivity.this.startActivity(intent);
					}else {
						Toast.makeText(NetAlbumActivity.this, "未下载图片", 2000).show();
					}

				}
				break;
			case 1:// 下載縮圖
				DownPhoto(uPhotosInfo.getS_url());
				break;
			case 2:// 下載原圖
				DownPhoto(uPhotosInfo.getB_url());
				
				break;

			default:

				break;
			}
			popupWindow.dismiss();

		}
	};

	private void getPhotos() {

		final RenrenAuthListener listener = new RenrenAuthListener() {

			@Override
			public void onComplete(Bundle values) {

				// 调用SDK异步接口获取相册
				new AsyncDownPhotos(renren, getBaseContext()).getPhotos(
						photosGetRequestParam,
						new AbstractRequestListener<PhotosGetResponseBean>() {
							@Override
							public void onRenrenError(
									final RenrenError renrenError) {
								NetAlbumActivity.this
								.runOnUiThread(new Runnable() {
									@Override
									public void run() {

										dismissProgress();
									}
								});
							}

							@Override
							public void onFault(final Throwable fault) {
								NetAlbumActivity.this
								.runOnUiThread(new Runnable() {
									@Override
									public void run() {
										// 查询出错，结束进度框，显示错误信息
										dismissProgress();
									}
								});
							}

							@Override
							public void onComplete(
									final PhotosGetResponseBean bean) {
								NetAlbumActivity.this
								.runOnUiThread(new Runnable() {
									@Override
									public void run() {
										photoList = bean.getPhotos();
										new AsyncTask<Object, Void, Void>() {
											@SuppressWarnings("unchecked")
											@Override
											protected Void doInBackground(
													Object... params) {
												List<PhotoBean> list = (List<PhotoBean>) params[0];
												NetAlbumDHhelper netAlbumDHhelper = new NetAlbumDHhelper(
														getBaseContext());
												if (!list.isEmpty()) {
													netAlbumDHhelper
													.clearAlbumPhotos(aid);
													for (PhotoBean photoBean : list) {
														// System.out.print(photoBean.toString());
														netAlbumDHhelper
														.addNetAlbumPhotos(photoBean);
													}
												}

												return null;
											}

										}.execute(photoList);
									}
								});

							}
						});

			}

			@Override
			public void onRenrenAuthError(RenrenAuthError renrenAuthError) {
				handler.post(new Runnable() {

					@Override
					public void run() {
						System.out.println("查询出错，结束进度框，显示错误信息3");
						Toast.makeText(
								NetAlbumActivity.this,
								NetAlbumActivity.this
								.getString(R.string.auth_failed),
								Toast.LENGTH_SHORT).show();
					}
				});
			}

			@Override
			public void onCancelLogin() {
			}

			@Override
			public void onCancelAuth(Bundle values) {
			}

		};

		thread.start();

		renren.authorize(NetAlbumActivity.this,
				NetAlbumsActivity.USER_PERMISSIONS, listener);

	}

	Thread thread = new Thread() {

		@Override
		public void run() {
			System.out.println("run");
			//读取数据库信息
			NetAlbumDHhelper netAlbumDHhelper = new NetAlbumDHhelper(
					getBaseContext());
			netPhotosInfos = netAlbumDHhelper.getNetPhotos(String.valueOf(aid));
			handlerResultHandler.sendEmptyMessage(0);

			while (true) {

				if (photoList.size() != 0) {

					System.out.println("handlerResultHandler");
					handlerResultHandler.sendEmptyMessage(1);
					return;
				}
			}

		}
	};
	Handler handlerResultHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			System.out.println("handleMessage");
			gridView = (GridView) findViewById(R.id.net_gridview);
			// 单击事件
			gridView.setOnItemClickListener(new OnItemClickListener() {



				// private String ablumName;

				@Override
				public void onItemClick(AdapterView<?> arg0, View View,
						int position, long arg3) {
					uPhotosInfo = netPhotosGridViewAdapter.get_netPhotosInfos().get(position);
					popupWindow.showAsDropDown(View);
				}

			});
			//屏幕分辨率
			w = (getWindowManager().getDefaultDisplay().getWidth() - 24) / 3;
			switch (msg.what) {
			case 0:
				netPhotosGridViewAdapter = new NetPhotosGridViewAdapter(
						NetAlbumActivity.this, netPhotosInfos);
				netPhotosGridViewAdapter.setGridviewSize(w);
				gridView.setAdapter(netPhotosGridViewAdapter);
				break;
			case 1:
				if (photoList.size() > 0) {
					netPhotosInfos.clear();
					for (PhotoBean photoBean : photoList) {
						netPhotosInfos.add(new NetPhotosInfo(photoBean));
						System.out.println("waiting...:"
								+ photoBean.getUrlTiny());
						// System.out.println("albumBean.getPhotos().size()"+photoBean.getPhotos().size());
					}
					if (netPhotosInfos.size() > 0) {
						netPhotosGridViewAdapter.clearConvertView();
						netPhotosGridViewAdapter
						.set_netPhotosInfos(netPhotosInfos);
						netPhotosGridViewAdapter.notifyDataSetChanged();
					}
				}
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 登出
	 */
	@Override
	protected void LoadOut() {
		try {
			Intent intent = new Intent();
			intent.putExtra("NetAlbumsActivity", 1);
			intent.setClass(NetAlbumActivity.this, NetAlbumsActivity.class);
			NetAlbumActivity.this.startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	//下载图片
	private void DownPhoto(final String s_url) {

		String fileName = Environment.getExternalStorageDirectory()
				.getPath()
				+ "/DCIM/Gallery2/_"
				+ s_url.split("/")[s_url.split("/").length - 1];
		System.out.println("DownPhoto:"+s_url);
		final File tempFile = new File(fileName);
		if(tempFile.exists()){
			Toast.makeText(this, "文件已经下载", Toast.LENGTH_LONG).show();
			return;
		}
		final Toast toast =Toast.makeText(this, "正在下载...", 999000);
		toast.show();
		// 从网络异步读取
		// 如果缓存过就会从缓存中取出图像，ImageCallback接口中方法也不会被执行
		AsyncPhotoLoader asyncPhotoLoader = new AsyncPhotoLoader();
		asyncPhotoLoader.loadDrawable(s_url,
				new AsyncPhotoLoader.ImageCallback() {
			// 如果第一次加载url时下面方法会执行
			public void imageLoaded(Drawable imageDrawable) {
				System.out.println("DownPhoto:"+s_url);
				System.out.println("DownPhoto:"+imageDrawable==null);
				Drawable cacheImage =imageDrawable;
				if (cacheImage != null) {
					Bitmap bitmap = Utils.drawableToBitmap(cacheImage);
					// 把图片写入到本地文件。
					if (Utils.getExternalStorageState()) {
						File file = new File(Environment.getExternalStorageDirectory()
								.getPath()
								+ "/DCIM/Gallery2/");
						if (!file.exists()) {
							file.mkdirs();
						}

						if (!tempFile.exists()) {
							try {
								tempFile.createNewFile();
								FileOutputStream fileOutputStream = new FileOutputStream(
										tempFile);
								bitmap.compress(CompressFormat.JPEG, 100, fileOutputStream);
								fileOutputStream.flush();
								fileOutputStream.close();

							} catch (Exception e2) {
								// TODO: handle exception
							}

						}
						Toast.makeText(NetAlbumActivity.this, "下载完成!", 2000).show();
						toast.cancel();
						// 回收资源
						if (bitmap != null && !bitmap.isRecycled()) {
							bitmap.recycle();
							bitmap = null;
						}
					}
				}else{
					Toast.makeText(NetAlbumActivity.this, "文件下载失败!", 2000).show();
				}
			}
		});

	}

	//换算
	private  int dip2px( float dipValue){ 
		final float scale = getResources().getDisplayMetrics().density; 
		return (int)(dipValue * scale + 0.5f); 
	}
}
